//
//  ClubChangeLogoViewController.swift
//  77Club
//
//  Created by Apple on 2024/12/30.
//

import UIKit
import ZLPhotoBrowser
import Photos

class ClubChangeLogoViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("论坛logo").color(.black).font(16.font_semiBold)
        .alignment(.center).end()
    private let saveButton = c_make_ex(UIButton.self)
        .image("Square_setting_save")
        .image("Square_setting_disSave", state: .disabled).end()
    private let imgButton = c_make_ex(UIImageView.self)
        .image("Forum_edit_logo").corner(8.0.Scale).end()
    private let delButton = c_make_ex(UIButton.self)
        .image("Forum_edit_del").end()
    private let subLabel = c_make_ex(UILabel.self)
        .text("限制一张，支持格式GIF/PNG/JPG").color("#969799")
        .font(12.font_medium).alignment(.center).end()
    
    private var images: [UIImage] = []
    private var assets: [PHAsset] = []
    private var imageUrl: String = ""
    
    var updateSquareLogo:((_:String)->())?
    
    var communityId = ""
    var logoUrl: String = "" {
        didSet{
            if logoUrl.count > 0 {
                imgButton.loadImage(url: logoUrl)
                delButton.isHidden = false
                saveButton.isEnabled = true
            }else{
                imgButton.image = "Forum_edit_logo".toImage
                delButton.isHidden = true
                saveButton.isEnabled = false
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            titleLabel
            saveButton
            imgButton.subviews{
                delButton
            }
            subLabel
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.centerHorizontally()
        titleLabel.CenterY == backButton.CenterY
        saveButton.trailing(0).top(.statusHeight).width(77).height(44)
        imgButton.top(.navi_height + 12.0.Scale).size(145.0.Scale).centerHorizontally()
        delButton.trailing(0).top(0).size(36.0.Scale)
        subLabel.centerHorizontally()
        subLabel.Top == imgButton.Bottom + 14
        
        let imgTap = UITapGestureRecognizer(target: self, action: #selector(addImgTap))
        imgButton.isUserInteractionEnabled = true
        imgButton.addGestureRecognizer(imgTap)
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        saveButton.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
        delButton.addTarget(self, action: #selector(clickDelButton), for: .touchUpInside)
    }

}

//MARK: action
extension ClubChangeLogoViewController {
    
    @objc private func clickSaveButton(){
        
        self.updateImage()
    }
    
    
    @objc private func clickDelButton(){
        
        self.logoUrl = ""
    }
    
    @objc private func addImgTap(){
        
        checkPhotoLibraryPermission()
    }
    
    
    private func checkPhotoLibraryPermission() {
         let status = PHPhotoLibrary.authorizationStatus()
             
         switch status {
             case .authorized:
                 // 已经授权，继续访问相册
             DispatchQueue.main.async {
                 self.showPhotoLibrary()
             }
                 
             case .denied, .restricted:
                 // 用户拒绝或受限，无法访问相册
                 print("用户拒绝访问相册")
             case .notDetermined:
                 // 用户还没有决定是否允许访问，进行请求
                 PHPhotoLibrary.requestAuthorization { newStatus in
                     if newStatus == .authorized {
                         // 用户授权，继续访问相册
                         DispatchQueue.main.async {
                             self.showPhotoLibrary()
                         }
                     } else {
                         print("用户拒绝访问相册")
                     }
                 }
         @unknown default:
                 print("未知的权限状态")
         }
     }
    
    private func showPhotoLibrary() {

        let config = ZLPhotoConfiguration.default()
        
        config.languageType = .chineseSimplified
        config.maxSelectCount = 1
        config.allowSelectGif = false
        config.allowMixSelect = false
        config.allowSelectVideo = false
        config.allowTakePhotoInLibrary = true
        config.allowEditVideo = true
        config.maxEditVideoTime = .max
        config.maxRecordDuration = .max
        config.maxSelectVideoDuration = .max
        config.saveNewImageAfterEdit = false
        config.editAfterSelectThumbnailImage = true
        config.allowSelectOriginal = false
        config.animateSelectBtnWhenSelect = false
        config.cropVideoAfterSelectThumbnail = true
        config.saveNewImageAfterEdit = false
        
        let ac = ZLPhotoPreviewSheet(selectedAssets:assets)
        
        ac.selectImageBlock = { [weak self] (images, assets, isOriginal) in
            self?.images = images
            self?.assets = assets
            self?.imgButton.image = images[0]
            self?.delButton.isHidden = false
            self?.saveButton.isEnabled = true
        }
        ac.showPhotoLibrary(sender: self)
    }
    
    private func updateImage(){
        
        RaeRequestParameterConfig.shared.uploadImage(uploadImage: self.images[0]) { urlString in
            self.imageUrl = urlString
            self.updateForumBGImg()
        } failure: { errorMessage in
            errorMessage.toast_error
        }
    }
    
    private func updateForumBGImg(){
        
        Task{
            ToastUtil.show()
            let models = await network.requestSpecial(.editSquareInfo(gid: communityId, field: "icon", value: self.imageUrl))
            ToastUtil.dismiss()
            if models.isSuccess {
                "修改成功~".toast_success
                self.updateSquareLogo?(self.imageUrl)
                self.navigationController?.popViewController(animated: true)
            }else{
                models.errorMessage?.toast_error
            }
        }
    }
}
